---
--类名: TaskManager.lua
--创建日期: 2017-6-22
--创建人: 陈小虎
--功能描述:
--修改内容:
--修改日期:
--修改人: galileoliu
--修改备注:
--
local BountyTaskInfo = import("..models.vo.BountyTaskInfo")
local DailyTaskInfo = import("..models.vo.DailyTaskInfo")

local TaskManager = class("TaskManager")

local string_split = string.split

function TaskManager:ctor()
    cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

    self._bountyTaskInfo = BountyTaskInfo.new()
    self._dailyTaskInfo = DailyTaskInfo.new()
    self._weeklyTaskInfo = DailyTaskInfo.new()

	self._baseShowIds = {}
	self._baseHideIds = {}
end

function TaskManager:init()
    -- 监听重连成功，如果是在战斗过程中，需要重新发起战斗
    EM:on("onReconnectSuccessed", function()
        print("onReconnectSuccessed task battle")
        local curTask = UD:getCurTask()
        if curTask then
            local conf = curTask:getConfig()
            local taskCreate = tonumber(conf.taskCreate)
            local createPar = conf.createPar
            if taskCreate == 1 and createPar then
                local array = string_split(createPar,"|")
                local battleId = tonumber(array[1])
                local dirNum = tonumber(array[2])
                local dir
                if dirNum == 1 then
                    dir = "right"
                elseif dirNum == 2 then
                    dir = "left"
                end
                -- 这里可能会出现问题，当玩家在跟随状态下，然后触发了这里，会报错的！
                BattleManager:storyBattleStart({battleId = battleId,dir = dir})
            end
        end
    end)

    -- 红点更新的三个状态
    -- 1、初始状态 2、有任务完成的时候 3、英雄之路有可领取的宝箱的时候 4、关闭任务界面的时候

    -- 更新主界面 任务的红点
    UD.badge:setNum(Constant.FUNC_TYPE_TASK, 0)
    UD.redPoint:setStateByKey(Constant.FUNC_TYPE_DAILY_TASK, false)

    -- 进游戏拉取一次英雄之路进度
    app:sendMsg("TaskModel", "reqRoadOfHeroProcess")

    -- 拉取赏金任务信息
    self:C2S_GetBountyTaskInfoRequest()

    -- TODO 拉取每周任务的奖励
    -- 进游戏拉取一次每日任务的奖励, 并更新主界面按钮红点
    self:C2S_GetDailyTaskInfoRequest(true)
end


-- 添加或删掉追踪任务
function TaskManager:saveTrackTask(key,value)
	UD:saveGeneric(key,value,function()
		app:dispatchCustomEvent("EVENT_UPDATE_TRACKLIST")
	end)
end

function TaskManager:isNeedTrack(taskId)
	local value = tonumber(UD:getValueFromGenericByKey(tostring(taskId))) or 0
	return (value ~= 0) and true
end

function TaskManager:getTaskDropItems(taskId,config)
	local taskC
	if not taskId then
		taskC = config
	else
		taskC = GD:queryTaskById(taskId)
	end

	if not taskC then return end
	local classId = tonumber(UD:getClass())
    local dropItems = {}
    for i = 1,5 do
    	local fieldName = "showReward" .. i
    	if taskC[fieldName] then
    		local rewardItemStr = string.gsub(taskC[fieldName],"{{.Class}}","" .. UD:getPlayer().classID)
    		local dropItem = UD:parseRewardToBagItem(rewardItemStr)
    		if dropItem then
    			table.insert(dropItems,dropItem)
    		end
    	end
    end
    return dropItems
end


function TaskManager:getCurrentTaskConfig()
    local task = UD:getCurTask()
    local taskConfig = task and task:getConfig() or nil
    return taskConfig
end

function TaskManager:getAllTaskConfigs()
    local taskConfigs = {}
    local tasks = UD:getCurTasks()
    for i,task in ipairs(tasks) do
        local taskConfig = task:getConfig()
        if taskConfig then
            table.insert(taskConfigs,taskConfig)
        end
    end
    return taskConfigs
end

function TaskManager:getAllTaskIds()
    local taskIds = {}
    local taskConfigs = self:getAllTaskConfigs()
    if taskConfigs then
        for i,v in ipairs(taskConfigs) do
            local taskConfig = v
            if taskConfig and taskConfig.ID then
                table.insert(taskIds,tonumber(taskConfig.ID))
            end
        end
    end
    return taskIds
end

function TaskManager:setCurrentTrackTaskId(taskId)
    self._taskTrackId = tonumber(taskId)
end

function TaskManager:getCurrentTrackTaskId()
    return self._taskTrackId or 0
end

function TaskManager:isCurrentTaskIdExsit()
    local taskIds = self:getAllTaskIds()
    if not taskIds then return end
    for i,v in ipairs(taskIds) do
        local taskId = tonumber(v)
        if taskId == self:getCurrentTrackTaskId() then
            return true
        end
    end
    return false
end

function TaskManager:setTaskNpcId(npcId)
	self._taskNpcId = npcId
end

function TaskManager:getTaskNpcId()
	return self._taskNpcId
end

function TaskManager:updateBaseShowIds()
	local showIds = {}
	local hideIds = {}
	-- local finishedConfigs = GD:queryMainTasksLessId(UD:getCurTaskId())
    local finishedConfigs = GD:queryPreMainTasks(UD:getCurTaskId())
    table.sort(finishedConfigs,function(a,b)
        return tonumber(a.ID) < tonumber(b.ID)
    end)

	for i,v in ipairs(finishedConfigs) do
		if v.basenpcShow then
			local array = string_split(v.basenpcShow,";")
			for i1,v1 in ipairs(array) do
				showIds[tonumber(v1)] = tonumber(v1)
			end
		end
		if v.basenpcHide then
			local array = string_split(v.basenpcHide,";")
			for i1,v1 in ipairs(array) do
				showIds[tonumber(v1)] = nil
				hideIds[tonumber(v1)] = tonumber(v1)
			end
		end
    end

	self._baseShowIds = showIds
	self._baseHideIds = hideIds
end

function TaskManager:getBaseNpcShowIds()
	return self._baseShowIds
end

function TaskManager:getBaseNpcHideIds()
	return self._baseHideIds
end

function TaskManager:isBaseNpcHide(npcId)
	return self._baseHideIds[tonumber(npcId)]
end

function TaskManager:setConversationNpcTaskMark(task, opt, isBranch)
	local npcTaskMark = task:getConfig().npcTab
	local taskConversationNpcId = tonumber(task:getConfig().condition1Par1) or 0
	local npc = NpcManager:getNpcById(taskConversationNpcId)
	if npc then
		if opt == "insert" and task:isTaken() then
			npc:setTaskId(task:getId())
			npc:setTaskMark(npcTaskMark)
            npc:resetMarkFromEvent()
		elseif opt == "update" and task:isFinished() then
			npc:setTaskMark(nil)
            npc:resetMarkFromEvent()
        elseif isBranch and opt == "delete" then
            npc:setTaskMark(nil)
            npc:resetMarkFromEvent()
		end
	end
end

function TaskManager:setNpcGatherMark(npcId)
	local npc = NpcManager:getNpcById(npcId)
	local npcC = NpcManager:getNpcConfigById(npcId)
	if npcC and npcC.ID and npc then
		local npcType = tonumber(npcC.type)
		npc:setGatherMark(npcType)
		npc:resetMarkFromEvent()
	end
end

function TaskManager:updateTaskOperation(task, opt, index)
	if not task then return end
--    print("======================> TaskManager:updateTaskOperation()")
--    print("opt", opt)
--    print("task.state", task:getId(), task.state)
    local taskConf = task:getConfig()
	local taskCreate = tonumber(taskConf.taskCreate)
	local createPar = taskConf.createPar
	local condition1Par1 = taskConf.condition1Par1
	local condition1Par2 = taskConf.condition1Par2
	local basenpcShow = taskConf.basenpcShow
	local basenpcHide = taskConf.basenpcHide
	local autoRun = taskConf.autoRun
	local npcType = tonumber(taskConf.npcType)
	local isAuto = (npcType == 2) and true or false
	local taskId = task:getId()

    -- 任务领完奖弹出提示
    local awardFlag = tonumber(taskConf.taskFinish)
    if awardFlag == 1 and task:isRewarded()  then
        local typeDesc = task:getTaskTypeDesc()
        local awardStr = string.format(L("TaskAccomplished"), typeDesc, L(taskConf.name))
        display.pushToast(awardStr)
    end

    -- print("00000000", task:getTaskTypeDesc(), task:getId(), task.state)

    -- 接受任务时生成地图baseNpc
	if basenpcShow and task:isTaken() and opt == "insert" then
		local array = string_split(basenpcShow,";")
		for i,v in ipairs(array) do
            -- 在任务回退的情况下，这个任务会重新接取。所以先把这个任务创建过的npc删除掉
            NpcManager:deleteNpcById(tonumber(v))
--            print("basenpc show id:", v)
            NpcFactory:createTaskNpcById(tonumber(v))
		end
	end

    -- 完成任务时删除地图baseNpc
	if basenpcHide and task:isFinished() and opt == "update" then
		local array = string_split(basenpcHide,";")
		for i,v in ipairs(array) do
--            print("basenpc hide id:", v)
			NpcManager:deleteNpcById(tonumber(v))
		end
    end

    -- 任务失败时隐藏当前任务显示的地图baseNpc
    if basenpcShow and task:isFinished() and opt == "delete" then
        local arrayShow = string_split(basenpcShow,";")
        for i,v in ipairs(arrayShow) do
--            print("Task fail basenpc hide id:", v)
            NpcManager:deleteNpcById(tonumber(v))
        end
    end


    -- 创建剧情临时NPC
    local function createTimeLimitNpc()
        local array
        local createNpcDelete = task:getConfig().createNpcDelete
        if createNpcDelete then
            array = string_split(createNpcDelete,"|")
        end
        if array and #array >= 3 then
            local mapId = tonumber(array[1])
            -- 如果在副本里，要判断是否为剧情副本
            if mapId == MapManager:getMapId() then
                if DungeonManager:isInDungeon() then
                    if DungeonManager:isTaskDungeon() then
                        NpcFactory:createTaskNpcById(tonumber(array[3]),tonumber(array[2]),isAuto,taskId)
                    end
                else
                    NpcFactory:createTaskNpcById(tonumber(array[3]),tonumber(array[2]),isAuto,taskId)
                end
            end
        end
    end

    -- 删除剧情临时NPC
    local function deleteTimeLimitNpc()
        local array
        local createNpcDelete = task:getConfig().createNpcDelete
        if createNpcDelete then
            array = string_split(createNpcDelete,"|")
        end
        if array and #array >= 3 then
            NpcManager:deleteNpcById(tonumber(array[3]))
        end
    end


    -- 接受任务时
    if taskCreate == 1 and createPar then
        if opt == "insert" and task:isTaken() then
            -- 接受时生成战斗
            local array = string_split(createPar,"|")
            local battleId = tonumber(array[1])
            local dirNum = tonumber(array[2])
            local dir
            if dirNum == 1 then
                dir = "right"
            elseif dirNum == 2 then
                dir = "left"
            end
            BattleManager:storyBattleStart({battleId = battleId,dir = dir}) -- 这里可能会出现问题，当玩家在跟随状态下，然后触发了这里，会报错的！
        end
    elseif taskCreate == 2 and createPar then
        local array = string_split(createPar,";")
        if opt == "insert" and task:isTaken() then
            -- 接受生成任务采集物
            for i,v in ipairs(array) do
                local nArray = string_split(v,"|")
                if #nArray >= 3 then
                    NpcFactory:createTaskNpcById(tonumber(nArray[3]),tonumber(nArray[2]),false,taskId,true)
                    self:setNpcGatherMark(tonumber(nArray[3]))
                end
            end
        elseif opt == "update" and task:isFinished() then
            -- 完成时删除任务采集物
            for i,v in ipairs(array) do
                local nArray = string_split(v,"|")
                if #nArray >= 3 then
                    NpcManager:deleteNpcById(tonumber(nArray[3]))
                end
            end
        end
    elseif taskCreate == 3 and createPar then
        local array = string_split(createPar,"|")
        if opt == "insert" and task:isTaken() then
            -- 接受时生成护送NPC
            if #array >= 2 then
                local npcId = tonumber(array[1])
                local bNpcId = tonumber(array[2])
                NpcFactory:createTaskNpcById(npcId,FieldManager:getCharacterX())
                FieldManager:addFollowNpc(npcId)
            end

            local cArray = string_split(autoRun,"|")
            if #cArray >= 2 then
                FieldManager:countFollowNpcBattlePoints(task,tonumber(cArray[1]),tonumber(cArray[2]))
            end
        elseif opt == "update" and task:isFinished() then
            -- 完成时删除护送NPC
            if #array >= 2 then
                local npcId = tonumber(array[1])
                local bNpcId = tonumber(array[2])
                NpcManager:deleteNpcById(npcId)
            end
        end
    elseif taskCreate == 4 then
        -- local array
        -- local createNpcDelete = task:getConfig().createNpcDelete
        -- if createNpcDelete then
        --     array = string_split(createNpcDelete,"|")
        -- end
        if opt == "insert" and task:isTaken() then
            -- 接受时创建剧情临时NPC
            -- if array and #array >= 3 then
            --     local mapId = tonumber(array[1])
            --     -- 如果在副本里，要判断是否为剧情副本
            --     if mapId == MapManager:getMapId() then
            --         if DungeonManager:isInDungeon() then
            --             if DungeonManager:isTaskDungeon() then
            --                 NpcFactory:createTaskNpcById(tonumber(array[3]),tonumber(array[2]),isAuto,taskId)
            --             end
            --         else
            --             NpcFactory:createTaskNpcById(tonumber(array[3]),tonumber(array[2]),isAuto,taskId)
            --         end
            --     end
            -- end

            createTimeLimitNpc()
        elseif opt == "update" and task:isFinished() then
            -- 完成时删除剧情临时NPC
            -- if array and #array >= 3 then
            --     NpcManager:deleteNpcById(tonumber(array[3]))
            -- end

            deleteTimeLimitNpc()
        end
        self:setConversationNpcTaskMark(task, opt)
    elseif taskCreate == 6 then -- 分支任务
        -- 只会有两种操作，一种insert，一种delete
        print("分支任务", opt, task:getId(), task.state) --@ignore
        if opt == "insert" then
            createTimeLimitNpc()
        elseif opt == "delete" then
            deleteTimeLimitNpc()
            if basenpcHide then
                local array = string_split(basenpcHide,";")
                for i,v in ipairs(array) do
--                    print("basenpc hide id:", v)
                    NpcManager:deleteNpcById(tonumber(v))
                end
            end
        end
        self:setConversationNpcTaskMark(task, opt, true)
    end

    if taskCreate ~= 3 then
        BattleManager:countDarkThunderBattlePoints(task, opt)
    end

    -- 这里只判断主线任务
	if opt == "update" and task:isMain() and task:isFinished() then
		if BattleManager:isInBattle() then
            self._delayMainFollowUpTaskId = taskId
		else
			DoEventHandler.startSingleFollowUpTaskEvents(taskId)
		end
	end

    if task:isMain() and task:isTaken() and opt == "insert" then
        -- 接受新的主线任务时，如果当前处于屏蔽主线任务追踪的状态，则关闭该状态并重新开启任务追踪
        if DoEventHandler.isTaskMaskFlag() then
            DoEventHandler.setTaskMaskFlag(false)
            UIHandler:enableMainTaskTrackingTouch()
        end

        -- 更新任务随从
        FieldManager:updateSelfTaskFollowMercenary(FieldManager:getSelfBaseInfo())
        -- 更新主线任务 特效
        UIHandler:updateMainTaskEffect()
        -- 更新主线任务控制的npc
        NpcFactory:createAllMainTaskNpc()
    end

     -- 检查支线任务, 接受的时候直接追踪
    if task:isSide() then
        if opt == "insert" and task:isTaken() then
             self:saveTrackTask(tostring(task:getId()), tostring(task:getId())) 
        elseif task:isFinished() then
            self:C2S_GetTaskRewardRequest("branch", task:getId())
        end
    end
end

function TaskManager:startDelayFollowUpTaskEvents()
	if not self._delayMainFollowUpTaskId then return end
	DoEventHandler.startSingleFollowUpTaskEvents(self._delayMainFollowUpTaskId)
	self._delayMainFollowUpTaskId = nil
end

function TaskManager:getTaskMinesConfigs(taskC)
	if not taskC or not taskC.ID then return end
	local minesC
	if taskC.mines then
		local minesArray = string_split(taskC.mines,";")
		if #minesArray > 0 then
			minesC = {}
		end
		for i,mine in ipairs(minesArray) do
			local mineC = GD:queryMineById(mine)
			if mineC and mineC.ID then
				table.insert(minesC,mineC)
			end
		end
	end
	return minesC
end

function TaskManager:getBattlePoints(task)
    local battlePoints = {}
    if task:getBattleIds() then
        local len = #task:getBattleIds()
        if len > 0 then
            local minesC = self:getTaskMinesConfigs(task:getConfig())
            if minesC then
                for i,mineC in ipairs(minesC) do
                    if mineC and mineC.ID then
                        local pointO = tonumber(mineC.coordinate)
                        local radius = tonumber(mineC.talkRadius)
                        local lx = pointO - radius
                        local lr = pointO + radius
                        local distance = radius * 2
                        local idis = math.floor(distance / (len + 1))
                        for i = 1,len do
                            local ePoint = {}
                            ePoint.x = lx + i * idis
                            ePoint.radius = 100
                            ePoint.battleId = tonumber(task:getBattleIds()[i])
                            ePoint.mine = mineC.ID
                            ePoint.finished = false
                            table.insert(battlePoints,ePoint)
                        end
                    end
                end
            end
        end
    end
    return battlePoints
end

function TaskManager:getDarkThunderBattlePoints(task)
    local battlePoints = {}
    local minesC = self:getTaskMinesConfigs(task:getConfig())
    if minesC then
        for i,mineC in ipairs(minesC) do
            if mineC and mineC.ID then
                local array = string_split(mineC.minePar1,"|")
                if #array >= 2 then
                    local time = math.random(tonumber(array[1]),tonumber(array[2]))
                    local pointO = tonumber(mineC.coordinate)
                    local radius = tonumber(mineC.talkRadius)
                    local lx = pointO - radius
                    local rx = pointO + radius
                    local mapId = tonumber(mineC.mapId)
                    local battlePoint = {
                        lx = lx,
                        rx = rx,
                        time = time,
                        moveTime = time - 2000,
                        mapId = mapId,
                        mine = mineC.ID,
                        taskId = task:getId(),
                        finished = false
                    }
                    table.insert(battlePoints,battlePoint)
                end
            end
        end
    end
    return battlePoints
end

function TaskManager:C2S_GetDailyTaskRewardRequest(boxIndex)
	app.session:request("pb_taskdaily.C2S_GetDailyTaskReward",{BoxIndex = boxIndex},function(msg)
		self:C2S_GetDailyTaskInfoRequest()
	end,{block = false},function(msg)
		if msg then

		end
	end)
end

function TaskManager:C2S_GetDailyTaskInfoRequest(bUpdate, cb)
	app.session:request("pb_taskdaily.C2S_GetDailyTaskInfo",{},function(msg)
        self._dailyTaskInfo:read(msg)
        self:dispatchEvent( {name = "GET_DAILY_QUESTINFO_OK"} )

        -- 更新主界面按钮红点
        if bUpdate then
            if self:checkHasRewardByTaskType() then
                UD.badge:setNum(Constant.FUNC_TYPE_TASK, 1)
            end
            
            if self:checkHasRewardByTaskType(2) then
                UD.redPoint:setStateByKey(Constant.FUNC_TYPE_DAILY_TASK, true)
            end
        end
        executeFunc(cb)
	end,{block = false},function(msg)
		if msg then

		end
	end)
end

function TaskManager:getDailyTaskInfo()
	return self._dailyTaskInfo
end

function TaskManager:C2S_GetWeeklyTaskInfoRequest()
    app.session:request("pb_taskweekly.C2S_GetWeeklyTaskInfo",{},function(msg)
        self._weeklyTaskInfo:read(msg)
        self:dispatchEvent({name = "GET_WEEKLY_QUESTINFO_OK"})
    end,{block = false},function(msg)
        if msg then

        end
    end)
end

function TaskManager:C2S_GetWeeklyTaskRewardRequest(needProgress)
    app.session:request("pb_taskweekly.C2S_GetWeeklyTaskReward",{NeedProgress = needProgress},function(msg)
        self:C2S_GetWeeklyTaskInfoRequest()
    end,{block = false},function(msg)
        if msg then

        end
    end)
end

function TaskManager:getWeeklyTaskInfo()
	return self._weeklyTaskInfo
end

function TaskManager:C2S_GetBountyTaskInfoRequest(callback)
	app.session:request("pb_taskbounty.C2S_GetBountyTaskInfo",{},function(msg)
        self._bountyTaskInfo:read(msg)
        -- 如果赏金任务全部完成，这里就清掉所有正在追踪的赏金任务
        if self:isBountyTaskFinished() then 
            local tasks = UD:getCurTakenBountyTasks()
            for _, task in ipairs(tasks) do
                if self:isNeedTrack(task:getId()) then
                    self:saveTrackTask(tostring(task:getId()), "0") 
                end 
            end
        end

        if callback then
            callback()
        end
        self:dispatchEvent({name = "GET_BOUNTY_INFO_OK"})
	end,{block = false},function(msg)
		if msg then

		end
	end)
end

function TaskManager:getBountyTaskInfo()
	return self._bountyTaskInfo
end

function TaskManager:isBountyTaskFinished()
    local finishedNum = self._bountyTaskInfo:getFinishedNum()
    local totalNum = self._bountyTaskInfo:getMaxNum()
    if finishedNum >= totalNum then
        return true
    end
    return false
end

function TaskManager:C2S_GetBountyTaskRequest(taskId)
	app.session:request("pb_taskbounty.C2S_GetBountyTask",{TaskID = taskId},function(msg)
		if msg and msg.ok then
			self:dispatchEvent({name = "GET_BOUNTY_TASK_OK"})
		end
	end,{block = false},function(msg)
		if msg then

		end
	end)
end

function TaskManager:C2S_RefreshBountyTaskRequest(taskId)
	app.session:request("pb_taskbounty.C2S_RefreshBountyTask",{TaskID = taskId},function(msg)
		if msg and msg.ok then
			self:C2S_GetBountyTaskInfoRequest(function()
				self:dispatchEvent({name = "REFRESH_BOUNTY_TASK_OK"})
				app:dispatchCustomEvent("EVENT_UPDATE_TRACKLIST")
			end)
		end
	end,{block = false},function(msg)
		if msg then

		end
	end)
end

function TaskManager:C2S_RefreshDailyTaskRequest(taskId)
    print("C2S_RefreshDailyTask", taskId)
    app.session:request("pb_taskdaily.C2S_RefreshDailyTask", {TaskID = taskId}, function(msg)
        if msg and msg.ok then
            self:C2S_GetDailyTaskInfoRequest(false, function()
                self:dispatchEvent({name = "REFRESH_DAILY_TASK_OK"})
            end)
        end
    end)
end

function TaskManager:relaunchGetTaskReward()
	local tasks = UD:getTasks()
	for k,task in pairs(tasks) do
		if task:isMain() and task:isFinished() then
			self:C2S_GetTaskRewardRequest(nil,task:getId())
		end
	end
end

function TaskManager:C2S_GetTaskRewardRequest(taskType, taskId)
	app.session:request("pb_task.C2S_GetTaskReward",{id = taskId},function(msg)
		if msg and msg.ok then
			if taskType == "bounty" then
				self:C2S_GetBountyTaskInfoRequest(function()
                    self:dispatchEvent({name = "REFRESH_BOUNTY_TASK_OK"})
                end)
            else
				self:dispatchEvent({name = "REFRESH_TASK_OK", taskType = taskType, taskId = taskId})
            end
            EM:notify(ViewEvent.Common_GetTaskReward, taskType, taskId)
		end
	end,{block = false},function(msg)
		if msg then

		end
	end)
end

function TaskManager:setGetTaskReward(isGet)
	self._isGetTaskReward = isGet
end

function TaskManager:isGetTaskReward()
	return self._isGetTaskReward
end

function TaskManager:storyGetTaskReward(taskId)
	local task = UD:getTaskById(taskId)
	if task and task:isMain() then
		self:C2S_GetTaskRewardRequest(nil,taskId)
	end
end

function TaskManager:C2S_TaskTalkRequest(taskId,callback)
    app.session:request("pb_task.C2S_TaskTalk",{id = taskId,npcId = self:getTaskNpcId()},function(msg)
        if msg.ok then
        	if callback then
        		callback()
        	end
        end
    end,{block = false},function(msg)

    end)
end

function TaskManager:C2S_TaskEscortRequest(taskId,npcId,callback)
	FieldManager:stopTouch(true)
	FieldManager:getMyCharacter():stopMove()
    app.session:request("pb_task.C2S_TaskEscort",{id = taskId,npcId = npcId},function(msg)
    	FieldManager:stopTouch(false)
        if msg.ok then
        	app:dispatchCustomEvent("ESCORT_FINISH_EVENT",{visible = true})
        	if callback then
        		callback()
        	end
        else
            app:popMessage("escortfail")
        end
    end,{block = false},function(msg)
        FieldManager:stopTouch(false)
        app:popMessage("escortfail")
    end)
end

function TaskManager:C2S_TaskGatherRequest(taskId,npcId,callback)
    app.session:request("pb_task.C2S_TaskGather",{id = taskId,npcId = npcId},function(msg)
        if msg.ok then
        	if callback then
        		callback()
        	end
        end
    end,{block = false},function(msg)

    end)
end

function TaskManager:C2S_TaskAcceptGrayBattleRequest(callback)
    app.session:request("pb_graybattle.C2S_AcceptGrayBattle",{},function(msg)
        if msg.ok then
            if callback then
                callback()
            end
        end
    end,{block = false},function(msg)

    end)
end

function TaskManager:C2S_TaskGetGrayBattleRewardRequest(callback)
    app.session:request("pb_graybattle.C2S_GetGrayBattleReward",{},function(msg)
        if msg.ok then
            if callback then
                callback()
            end
        end
    end,{block = false},function(msg)

    end)
end

-- 主线任务选择分支
function TaskManager:reqSelectMainTask(nowTaskId, nextTaskId)
    print("reqSelectMainTask", nowTaskId, nextTaskId)
    app.session:request("pb_task.C2S_TaskSelect", {nowTaskId = nowTaskId, tarTaskId = nextTaskId}, function(msg)
        if msg.ok then
            display.pushToast(L("lua_code_text_473"))
        else
            display.pushToast(L("lua_code_text_16"))
        end
    end)
end

-- 返回每日任务可领而没领的宝箱个数
function TaskManager:getDailyTaskRewardNum()
    local iCount = 0
    local finishNum = #UD:getFinishedDailyTasks()
    local dailyTaskProgress = self._dailyTaskInfo:getDailyTaskProgress()
    if not dailyTaskProgress then dailyTaskProgress = {} end
    for _, progress in ipairs(dailyTaskProgress) do
        if progress.NowProgress > 0 and finishNum >= tonumber(progress.NeedProgress) then
            iCount = iCount + progress.NowProgress
        end
    end

    return iCount
end

-- 返回每日任务宝箱总数量
function TaskManager:getDailyTaskAwardBoxCount()
    return self._dailyTaskInfo:getRewardNum()
end

-- 返回每日任务可刷新次数
function TaskManager:getDailyTaskRefreshNum(pos)
    return self._dailyTaskInfo:getRefreshNum(pos)
end


-- 根据任务类型检查是否有已完成的任务（未领奖）
function TaskManager:checkHasRewardByTaskType(iType)
    if iType == 2 then -- 每日任务
        local tasks = UD:getTotalDailyTasks()
        for _, task in ipairs(tasks) do
            if task:isFinished() then return true end
        end
        -- 是否有礼包未领取
        if self:getDailyTaskRewardNum() > 0 then 
            return true
        end
    end
    if iType == nil or iType == 3 then -- 每周任务
        local tasks = UD:getAllWeeklyTasks()
        for _, tasks in ipairs(tasks) do
            if task:isFinished() then return true end
        end
        -- 是否有礼包未领取
        local finishNum = #UD:getFinishedWeeklyTasks()
        local arrStr = string_split(GD:getSystemStrPar("weeklyQuestRewardslimit"), "|")
        for i = 1, 3 do
            local rewardProgress = self._weeklyTaskInfo:getTaskRewardProgress(tonumber(arrStr[i]))
            if rewardProgress and rewardProgress.NowProgress > 0 and finishNum >= tonumber(rewardProgress.NeedProgress) then
                return true
            end
        end
    end
    if iType == nil or iType == 4 then -- 赏金任务
        -- 查看是否已完成本周全部的赏金任务
        if self._bountyTaskInfo and self._bountyTaskInfo:getFinishedNum() >= self._bountyTaskInfo:getMaxNum() then
            -- do nothing
        else
            local tasks = UD:getTotalBountyTasks()
            for _, task in ipairs(tasks) do
                if task:isFinished() then return true end
            end
        end
    end

    if iType == nil or iType == 100 then -- 英雄之路
        local process = app:sendMsg("TaskModel", "getRoadOfHeroProcess")
        return process and process:checkHasAward()
    end

    return false
end

return TaskManager
